﻿using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;
using Microsoft.Web.Helpers;
using VideoSeller.Business.Data.Enums;
using VideoSeller.Business.Providers;
using VideoSeller.Core.Configuration;
using VideoSeller.Core.Interfaces;
using VideoSeller.Web.App_Start;
namespace VideoSeller.Web
{
	public class MvcApplication : HttpApplication
	{
		private static IWindsorContainer _container;

		protected void Application_Start()
		{
			BootstrapContainer();
			ViewEngines.Engines.Clear();
			ViewEngines.Engines.Add(new RazorViewEngine());
			AreaRegistration.RegisterAllAreas();
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);
			CreateDefaultUsersAndRoles();
			ReCaptcha.PublicKey = "6LcE6OISAAAAALT1cyBppOqhxvBU0_32YOi0F2af";
			ReCaptcha.PrivateKey = "6LcE6OISAAAAAEdkOjt3DYqHKSdEVIRNuxhbLH_R";
		}

		protected void Application_End()
		{
			_container.Dispose();
		}

		private static void BootstrapContainer()
		{
			_container = new WindsorContainer().Install(FromAssembly.Named("VideoSeller.Core"));
			_container.Register(Component.For<IApplicationSettingsProvider>().ImplementedBy<ApplicationSettingsProvider>().LifeStyle.Singleton);
			_container.Register(Component.For<IDatabaseSettingsProvider>().ImplementedBy<DatabaseSettingsProvider>().LifeStyle.Singleton);
			_container.Register(Component.For<IMailProvider>().ImplementedBy<SmtpClientProvider>().LifeStyle.Singleton);
			IoC.Initialize(_container);
			var controllerFactory = new WindsorControllerFactory(_container.Kernel);
			ControllerBuilder.Current.SetControllerFactory(controllerFactory);
		}

		private void CreateDefaultUsersAndRoles()
		{
			if (!Roles.RoleExists(UserRole.Administrator.ToString()))
			{
				Roles.CreateRole(UserRole.Administrator.ToString());
			}

			if (!Roles.RoleExists(UserRole.Moderator.ToString()))
			{
				Roles.CreateRole(UserRole.Moderator.ToString());
			}

			if (!Roles.RoleExists(UserRole.User.ToString()))
			{
				Roles.CreateRole(UserRole.User.ToString());
			}
		}
	}
}